package io.github.yotta.logger.message;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.github.yotta.logger.message.consumer.AbstractLogDataConsumer;
import io.github.yotta.logger.message.consumer.EventBusLogDataConsumer;
import io.github.yotta.logger.message.producer.EventBusLogDataProducer;
import io.github.yotta.logger.message.producer.LogDataProducer;
import io.github.yotta.logger.message.support.LogSaveProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yotta
 * @date 2023/3/22 19:26
 */
@Configuration
@Slf4j
public class EventBusLogDataProducerAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean({EventBus.class})
    public EventBus eventBus() {
        int processors = Runtime.getRuntime().availableProcessors();
        ExecutorService executor = Executors.newFixedThreadPool(processors, (new ThreadFactoryBuilder()).setNameFormat("AsyncEventBusPool-%d").build());
        return new AsyncEventBus(executor);
    }

    @Bean
    @ConditionalOnMissingBean({LogDataProducer.class})
    public LogDataProducer logDataProducer(EventBus eventBus) {
        return new EventBusLogDataProducer(eventBus);
    }

    @Bean
    @ConditionalOnMissingBean({AbstractLogDataConsumer.class})
    public AbstractLogDataConsumer logDataConsumer(EventBus eventBus, LogSaveProvider saveProvider) {
        final EventBusLogDataConsumer eventBusLogDataConsumer = new EventBusLogDataConsumer(saveProvider);
        eventBus.register(eventBusLogDataConsumer);
        return eventBusLogDataConsumer;
    }
}
